<template>
  <div style="border: 1px solid #ccc;z-index:1001;">
    <toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <editor
      style="height: 350px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted, watch} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {getToken} from "@/utils/token-util.js"


const BASE_URL = import.meta.env.BASE_URL;
const VITE_API_URL = import.meta.env.VITE_API_URL;


const props = defineProps({
  /** v-model */
  modelValue: String
});


const emit = defineEmits(['update:modelValue']);

/** 更新value */
const updateValue = (value) => {
  emit('update:modelValue', value);
};


const toolbarConfig = {
  // 插入哪些菜单
  insertKeys: {
    index: 23, // 自定义插入的位置
    keys: ['uploadAttachment'], // “上传附件”菜单
  },

};

const editorConfig = {
  height: 200,
  placeholder: '欢迎使用福州大学至诚学院就业管理系统',
  // 在编辑器中，点击选中“附件”节点时，要弹出的菜单
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
  },
  MENU_CONF: {
    // 上传附件的菜单配置
    uploadAttachment: {
      server: VITE_API_URL + '/admin/cms/common/wangEditor/upload/file', //文件上传地址
      timeout: 10 * 1000, // 10s
      fieldName: 'file',
      metaWithUrl: true, // 参数拼接到 url 上
      headers: {Accept: 'application/json', Authorization: getToken()},
      maxFileSize: 10 * 1024 * 1024, // 10M
      onBeforeUpload(file) {
        //console.log('onBeforeUpload', file)
        return file // 返回哪些文件可以上传
        // return false // 会阻止上传
      },
      onProgress(progress) {
        //console.log('onProgress', progress)
      },
      onSuccess(file, res) {
        //console.log('onSuccess', file, res)
      },
      onFailed(file, res) {
        alert(res.message)
        console.log('onFailed', file, res)
      },
      onError(file, err, res) {
        alert(err.message)
        console.error('onError', file, err, res)
      },
      // // 用户自定义插入文件
      // customInsert(res: any, file: File, insertFn: Function) {
      //   console.log('customInsert', res)
      //   const { url } = res.data || {}
      //   if (!url) throw new Error(`url is empty`)

      //   // 自己插入附件
      //   insertFn(`customInsert-${file.name}`, url)
      // },

      // // 用户自定义上传
      // customUpload(file: File, insertFn: Function) {
      //   console.log('customUpload', file)

      //   return new Promise(resolve => {
      //     // 插入一个文件，模拟异步
      //     setTimeout(() => {
      //       const src = `https://www.w3school.com.cn/i/movie.ogg`
      //       insertFn(`customUpload-${file.name}`, src)
      //       resolve('ok')
      //     }, 500)
      //   })
      // },

      // // 自定义选择
      // customBrowseAndUpload(insertFn: Function) {
      //   alert('自定义选择文件，如弹出图床')
      // },

      // onInsertedAttachment(elem: AttachmentElement) {
      //   console.log('inserted attachment', elem)
      // },
    }
  }
};


// editorConfig.MENU_CONF['uploadImage'] = {
//   server: '/api/upload-img',
//   timeout: 10 * 1000, // 10s
//   fieldName: 'custom-fileName',
//   meta: {token: 'xxx', a: 100},
//   maxFileSize: 10 * 1024 * 1024, // 10M
//   base64LimitSize: 5 * 1024,
//   onBeforeUpload(file) {
//     console.log('onBeforeUpload', file)
//
//     return file // will upload this file
//     // return false // prevent upload
//   },
//   onProgress(progress) {
//     console.log('onProgress', progress)
//   },
//   onSuccess(file, res) {
//     console.log('onSuccess', file, res)
//   },
//   onFailed(file, res) {
//     alert(res.message)
//     console.log('onFailed', file, res)
//   },
//   onError(file, err, res) {
//     alert(err.message)
//     console.error('onError', file, err, res)
//   },
// }

//配置行高选项
editorConfig.MENU_CONF['lineHeight'] = {
  lineHeightList: ['1', '1.5', '2', '2.5'],
}
//配置字体
editorConfig.MENU_CONF['fontFamily'] = {
  fontFamilyList: [
    // 元素支持两种形式
    //   1. 字符串；
    //   2. { name: 'xxx', value: 'xxx' }
    '微软雅黑',
    '宋体',
    '黑体',
    '楷体',
    'Arial'
  ],
}

//配置图片上传地址
editorConfig.MENU_CONF['uploadImage'] = {
  server: VITE_API_URL + '/admin/cms/common/wangEditor/upload/file', //图片上传地址,
  timeout: 10 * 1000, // 10s
  fieldName: 'file',
  metaWithUrl: true, // 参数拼接到 url 上
  headers: {Accept: 'application/json', Authorization: getToken()},
  maxFileSize: 10 * 1024 * 1024, // 10M
  onBeforeUpload(file) {
    console.log('onBeforeUpload', file)
    return file // 返回哪些文件可以上传
    // return false // 会阻止上传
  },
  onProgress(progress) {
    console.log('onProgress', progress)
  },
  onSuccess(file, res) {
    console.log('onSuccess', file, res)
  },
  onFailed(file, res) {
    alert(res.message)
    console.log('onFailed', file, res)
  },
  onError(file, err, res) {
    alert(err.message)
    console.error('onError', file, err, res)
  },
}

//配置视频上传地址
editorConfig.MENU_CONF['uploadVideo'] = {
  server: VITE_API_URL + '/admin/cms/common/wangEditor/upload/file', //视频上传地址,
  timeout: 60 * 1000, // 60s
  fieldName: 'file',
  metaWithUrl: true, // 参数拼接到 url 上
  headers: {Accept: 'application/json', Authorization: getToken()},
  maxFileSize: 100 * 1024 * 1024, // 100M
  onBeforeUpload(file) {
    console.log('onBeforeUpload', file)
    return file // 返回哪些文件可以上传
    // return false // 会阻止上传
  },
  onProgress(progress) {
    console.log('onProgress', progress)
  },
  onSuccess(file, res) {
    console.log('onSuccess', file, res)
  },
  onFailed(file, res) {
    alert(res.message)
    console.log('onFailed', file, res)
  },
  onError(file, err, res) {
    alert(err.message)
    console.error('onError', file, err, res)
  },
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
//编辑器内容
const valueHtml = ref('');
onMounted(() => {
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  console.log("编辑器已经销毁");
  const editor = editorRef.value
  if (editor == null) {
    return;
  }
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor;
  if (props.modelValue) {
    valueHtml.value = props.modelValue;
  }
}

const mode = ref("default");

//当边编辑器出现修改时，同步更新modelValue
const handleChange = (editor) => {
  emit('update:modelValue', valueHtml.value);
}

</script>
